package com.mdd.front.service.product.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.car.entity.CarBrand;
import com.mdd.car.mapper.CarBrandMapper;
import com.mdd.car.vo.CarBrandVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.agreement.RiskControl;
import com.mdd.common.entity.car.CarProductList;
import com.mdd.common.entity.order.OrderClueList;
import com.mdd.common.entity.setting.DictData;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.risk.RiskControlMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.front.LikeFrontThreadLocal;
import com.mdd.front.service.leasing.ILeasingSchemeFrontService;
import com.mdd.front.service.product.IProductPropertyFrontService;
import com.mdd.front.service.product.IProductSkuFrontService;
import com.mdd.front.service.product.IProductSpuFrontService;
import com.mdd.front.validate.car.CarSpuSearchValidate;
import com.mdd.front.validate.product.ProductSpuSearchValidate;
import com.mdd.front.vo.car.CarInitDataVo;
import com.mdd.front.vo.car.CarSpuDetailVo;
import com.mdd.front.vo.car.CarSpuListVo;
import com.mdd.front.vo.sku.ProductSkuVo;
import com.mdd.front.vo.spu.MallSpuVo;
import com.mdd.front.vo.spu.ProductSpuDetailVo;
import com.mdd.front.vo.spu.ProductSpuVo;
import com.mdd.front.vo.user.UserBindInfoVo;
import com.mdd.product.entity.ProductSpu;
import com.mdd.product.mapper.ProductSpuMapper;
import com.mdd.store.api.StoreApi;
import com.mdd.system.mapper.dict.DictDataMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.*;

/**
 * 商品实现类
 * @author LikeAdmin
 */
@Service
public class ProductSpuFrontServiceImpl implements IProductSpuFrontService {
    @Resource
    ProductSpuMapper productSpuMapper;
    @Resource
    StoreApi storeApi;
    @Resource
    IProductSkuFrontService iProductSkuFrontService;
    @Resource
    IProductPropertyFrontService iProductPropertyFrontService;
    @Resource
    ILeasingSchemeFrontService iLeasingSchemeFrontService;
    @Resource
    RiskControlMapper riskControlMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    CarBrandMapper carBrandMapper;
    @Resource
    DictDataMapper dictDataMapper;
    /**
     * 商品列表
     *
     * @param searchValidate 搜索参数
     * @return PageResult<ProductSpuListedVo>
     * @author LikeAdmin
     */
    @Override
    public PageResult<ProductSpuVo> page(ProductSpuSearchValidate searchValidate) {
        int page = null != searchValidate ? searchValidate.getPageNo() : 1;
        int limit = null != searchValidate ? searchValidate.getPageSize() : 10;
        Assert.isTrue(storeApi.isExists(searchValidate.getStoreId()),"门店id错误，该门店不存在!");
        LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(searchValidate.getName())) {
            queryWrapper.like(ProductSpu::getName, searchValidate.getName());
        }
        queryWrapper.eq(ProductSpu::getStatus,0);
        queryWrapper.likeRight(ProductSpu::getDeptCode,storeApi.getDeptCode(searchValidate.getStoreId()));
        queryWrapper.orderByDesc(ProductSpu::getSort);

        IPage<ProductSpu> iPage = productSpuMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<ProductSpuVo> list = new LinkedList<>();
        for (ProductSpu item : iPage.getRecords()) {
            ProductSpuVo vo = new ProductSpuVo();
            BeanUtils.copyProperties(item, vo);
            vo.setAmountStr( iLeasingSchemeFrontService.getFirstAmountStr(item.getId()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 商品详情
     *
     * @param id 主键参数
     * @return ProductSpu
     * @author LikeAdmin
     */
    @Override
    public ProductSpuDetailVo detail(Long id) {
        ProductSpu model = productSpuMapper.selectById(id);

        Assert.notNull(model, "spu数据不存在");

        ProductSpuDetailVo vo = new ProductSpuDetailVo();
        BeanUtils.copyProperties(model, vo);

        List<ProductSkuVo> list = iProductSkuFrontService.list(id);
        vo.setSkus(list);
        vo.setPropertyList(iProductPropertyFrontService.list(id));
        UserBindInfoVo userBindInfoVo = new UserBindInfoVo();
        User user= userMapper.selectById(LikeFrontThreadLocal.getUserId());
        if(StringUtils.isNotEmpty(user.getRealName())&&StringUtils.isNotEmpty(user.getCardNo())&& StringUtils.isNotEmpty(user.getMobile())){
            userBindInfoVo.setBindFlag(true);
            userBindInfoVo.setRealName(user.getRealName());
            userBindInfoVo.setMobile(user.getMobile());
            userBindInfoVo.setCardNo(user.getCardNo());
        }else {
            userBindInfoVo.setBindFlag(false);
        }
        vo.setUserBindInfo(userBindInfoVo);
        //获取风控
        RiskControl riskControl = riskControlMapper.selectOne(new LambdaQueryWrapper<RiskControl>().eq(RiskControl::getUserId, LikeFrontThreadLocal.getUserId() )
        .last("limit 1").orderByDesc(RiskControl::getVersion));
        //0-10免押金，10-30，押金50%，30以上100%押金
        if(Objects.isNull(riskControl)){
            vo.setLeasingSchemes(iLeasingSchemeFrontService.list(id,null));
        }else{
            vo.setLeasingSchemes(iLeasingSchemeFrontService.list(id, riskControl.getRiskScore()));

        }

        return vo;
    }

    @Override
    public PageResult<MallSpuVo> mallPage(ProductSpuSearchValidate searchValidate) {
        int page = null != searchValidate ? searchValidate.getPageNo() : 1;
        int limit = null != searchValidate ? searchValidate.getPageSize() : 10;
        LambdaQueryWrapper<ProductSpu> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(searchValidate.getName())) {
            queryWrapper.like(ProductSpu::getName, searchValidate.getName());
        }
        queryWrapper.eq(ProductSpu::getStatus,0);
        //查询如通上传租赁方案
        queryWrapper.eq(ProductSpu::getDeptId,"1");
        queryWrapper.orderByDesc(ProductSpu::getSort);

        IPage<ProductSpu> iPage = productSpuMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<MallSpuVo> list = new LinkedList<>();
        for (ProductSpu item : iPage.getRecords()) {
            MallSpuVo vo = new MallSpuVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }
    /**
     * 商品详情
     *
     * @param id 主键参数
     * @return ProductSpu
     * @author LikeAdmin
     */
    @Override
    public ProductSpuDetailVo mallDetail(Long id) {
        ProductSpu model = productSpuMapper.selectById(id);

        Assert.notNull(model, "spu数据不存在");

        ProductSpuDetailVo vo = new ProductSpuDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setLeasingSchemes(iLeasingSchemeFrontService.list(id, null));
        return vo;
    }

    @Override
    public CarInitDataVo initCarProductData() {
        CarInitDataVo carInitDataVo = new CarInitDataVo();
        List<CarBrand> carBrands = carBrandMapper.selectList(new QueryWrapper<>());
        List<CarBrandVo> carBrandVoList = new ArrayList<>();
        carBrands.forEach(carBrand -> {
            CarBrandVo carBrandVo = new CarBrandVo();
            BeanUtils.copyProperties(carBrand,carBrandVo);
            carBrandVoList.add(carBrandVo);
        });
        carInitDataVo.setCarBrandVoList(carBrandVoList);
        List<DictData> dictDataList = dictDataMapper.selectList(new LambdaQueryWrapper<DictData>().eq(DictData::getTypeId,5));
        carInitDataVo.setColumnDictList(dictDataList);
        List<String> keyWord = new ArrayList<>(3);
        keyWord.add("纯电");
        keyWord.add("油车");
        keyWord.add("混动");
        carInitDataVo.setKeyWord(keyWord);
        return carInitDataVo;
    }

    @Override
    public PageResult<CarSpuListVo> page(CarSpuSearchValidate searchValidate) {
        int page = null != searchValidate.getPageNo() ? searchValidate.getPageNo() : 1;
        int limit = null != searchValidate.getPageSize() ? searchValidate.getPageSize() : 10;


        Map params = new HashMap<>();
        if (Objects.nonNull(searchValidate.getStoreId())) {
            params.put("storeId",searchValidate.getStoreId());
        }
        if (StringUtils.isNotEmpty(searchValidate.getKeyword())) {
            params.put("keyword", searchValidate.getKeyword());
        }
        if (Objects.nonNull(searchValidate.getCarBrandId())) {
            params.put("brandId", searchValidate.getCarBrandId());
        }
        if (Objects.nonNull(searchValidate.getColumn())) {
            params.put("columnId", searchValidate.getColumn());
        }
        params.put("type",searchValidate.getType());

        IPage<CarProductList> iPage = productSpuMapper.selectCarProductPage(
                new Page<>(page, limit), params);
        List<CarSpuListVo> carSpuListVoList = new ArrayList<>();
        iPage.getRecords().forEach(orderClue -> {
            CarSpuListVo carSpuListVo = new CarSpuListVo();
            BeanUtils.copyProperties(orderClue,carSpuListVo);
            carSpuListVoList.add(carSpuListVo);
        });
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), carSpuListVoList);
    }

    @Override
    public CarSpuDetailVo carSpuDetail(Long id) {
        ProductSpu productSpu = productSpuMapper.selectById(id);
        Assert.notNull(productSpu,"不存在该商品！");
        CarBrand carBrand = carBrandMapper.selectById(productSpu.getBrandId());
        CarSpuDetailVo carSpuDetailVo = new CarSpuDetailVo();
        BeanUtils.copyProperties(productSpu,carSpuDetailVo);
        carSpuDetailVo.setBrandName(carBrand.getBrandName());
        return carSpuDetailVo;
    }

}
